package com.fading.mall.product.exception;


import com.fading.common.exception.MallCode;
import com.fading.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;

@RestControllerAdvice(basePackages = "com.fading.mall.product.controller")
@Slf4j
public class MallException {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleAllException(MethodArgumentNotValidException e){
        BindingResult result = e.getBindingResult();
        HashMap<String, String> map = new HashMap<>();
        result.getFieldErrors().forEach((error)->
                map.put(error.getField(), error.getDefaultMessage())
                );
        log.error("数据校验发现错误 {}，异常类型 {}",e.getMessage(),e.getClass());
        return R.error(MallCode.VALIDATE_EXCEPTION.getCode(),MallCode.VALIDATE_EXCEPTION.getMsg()).put("message", map);
    }

    @ExceptionHandler(value = Throwable.class)
    public R handleOtherThrowable(Throwable throwable){
        return R.error(MallCode.UNKNOW_EXCEPTION.getCode(), MallCode.UNKNOW_EXCEPTION.getMsg());
    }







}
